<?php
namespace Jykj\Mass\Controller;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
include_once(ExtensionManagementUtility::extPath('mass') . 'Classes/SDK/api_demo/SmsDemo.php');

/***************************************************************
 *
 *  Copyright notice
 *
 *  (c) 2017 WHB <wanghongbin@ngoos.org>, 极益科技
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

/**
 * SmsController
 */
class SmsController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{

    /**
     * smsRepository
     *
     * @var \Jykj\Mass\Domain\Repository\SmsRepository
     * @inject
     */
    protected $smsRepository = NULL;
    
    /**
     * logRepository
     *
     * @var \Jykj\Mass\Domain\Repository\LogRepository
     * @inject
     */
    protected $logRepository = NULL;
    

    /**
     * action initialize
     *
     * @return void
     */
    public function initializeAction()
    {
        
    }


    /**
     * action list
     *
     * @return void
     */
    public function listAction()
    {
        $svalid = $this->request->hasArgument('svalid') ? $this->request->getArgument('svalid') : '';
        $evalid = $this->request->hasArgument('evalid') ? $this->request->getArgument('evalid') : '';
        $keyword = $this->request->hasArgument('keyword') ? $this->request->getArgument('keyword') : '';
        $smss = $this->smsRepository->findAlls($svalid, $evalid, $keyword);
        if ($_GET['tx_mass_sms']['@widget_0']['currentPage']) {
            $page = $_GET['tx_mass_sms']['@widget_0']['currentPage'];
        } else {
            $page = 1;
        }
        $this->view->assign('page', $page);
        $this->view->assign('smss', $smss);
        $this->view->assign('svalid', $svalid);
        $this->view->assign('evalid', $evalid);
        $this->view->assign('keyword', $keyword);
        $this->view->assign('form', GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));

        //excel export
        if($this->request->hasArgument('excelExport')){
            $phpExcelService = GeneralUtility::makeInstanceService('phpexcel');
            $phpExcel = $phpExcelService->getPHPExcel();
            $sheet  = $phpExcel->setActiveSheetIndex(0);
            $dataArray[] = array('序号', '短信签名', '短信模板编号', '发送时间', '发送状态', '成功率', '总计');
            if(count($smss)){
                $i = 1;
                foreach($smss as $sms){
                    $dataArray[] = array(
                        $i++,
                        $sms->getSender(),
                        $sms->getModelNum(),
                        date('Y-m-d H:i', $sms->getCrdate()),
                        $sms->getSendStatus()==0?'未发送':'已发送',
                        $sms->getSuccessRate().'%',
                        $sms->getTotal().'条'
                    );
                }
                $sheet->fromArray($dataArray, NULL, 'A1');
                $objWriter = $phpExcelService->getInstanceOf('PHPExcel_Writer_Excel2007', $phpExcel);
                $fileName = '群发短信列表_'.date('Y-m-d');
                header('Pragma: public');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Content-Type: application/force-download');
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
                header('Cache-Control: max-age=0');
                $objWriter->save('php://output');
                exit;
            }
        }
    }
    
    /**
     * action show
     *
     * @param \Jykj\Mass\Domain\Model\Sms $sms
     * @return void
     */
    public function showAction(\Jykj\Mass\Domain\Model\Sms $sms)
    {
        $this->view->assign('sms', $sms);
    }
    
    /**
     * action new
     *
     * @return void
     */
    public function newAction()
    {
        //excel import
        if ($this->request->hasArgument('receiver')) {
            $file = $this->request->getArgument('receiver');
            $fI = GeneralUtility::split_fileref($file['name']);
            if (GeneralUtility::inList('xls,xlsx', $fI['fileext'])) {
                $objPHPReader = $this->objectManager->get($fI['fileext'] == 'xls' ? 'PHPExcel_Reader_Excel5' : 'PHPExcel_Reader_Excel2007');
                $objPHPExcel = $objPHPReader->load($file['tmp_name']);
                $currentSheet = $objPHPExcel->getSheet(0);
                $allRow = $currentSheet->getHighestRow();
                $i = 0;
                $telStr = '';
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    if ($currentSheet->getCell('B' . $currentRow)->getValue() != '') {
                        $name = $currentSheet->getCell('A' . $currentRow)->getValue();
                        $tel = $currentSheet->getCell('B' . $currentRow)->getValue();
                        $telStr .= $name . '<' . $tel . '>,';
                        $i++;
                    }
                }
                $telStr = rtrim($telStr, ',');
                $sms = new \Jykj\Mass\Domain\Model\Sms();
                $sms->setRecriver($telStr);
                $this->view->assign('sms', $sms);
                $this->addFlashMessage('已成功上传“' . $i . '”条数据', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            } else {
                $this->addFlashMessage('文件格式不正确，请上传xls, xlsx格式文件。', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            }
        }
        $signatureArray = array();
        $tempArray = GeneralUtility::trimExplode('|', $this->settings['signature']);
        foreach ($tempArray as $signature) {
            $signatureArray[$signature] = $signature;
        }
        $this->view->assign('signatureArray', $signatureArray);
        $smsTemplateArray = array();
        $tempArray = GeneralUtility::trimExplode('|', $this->settings['templates']);
        foreach ($tempArray as $template) {
            $dataArray = GeneralUtility::trimExplode('^', $template);
            $smsTemplateArray[$dataArray[0]] = $dataArray[0] . ' - ' . $dataArray[1];
        }
        $this->view->assign('smsTemplateArray', $smsTemplateArray);
    }
    
    /**
     * action create
     *
     * @param \Jykj\Mass\Domain\Model\Sms $sms
     * @return void
     */
    public function createAction(\Jykj\Mass\Domain\Model\Sms $sms)
    {
        if ($sms->getSendStatus() == 0) {
            $this->addFlashMessage('短信已保存为草稿！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            $this->smsRepository->add($sms);
        } else {
            $receiverStr = $sms->getRecriver();
            $modelNum = $sms->getModelNum();
            $receiverArr = $this->getNameAndTel($receiverStr);
            $countUp = count(GeneralUtility::trimExplode(',', $receiverStr));
            $countOn = count($receiverArr);
            $percent = sprintf('%.2f', $countOn / $countUp) * 100;
            $sms->setTotal($countOn);
            $sms->setSendStatus(1);
            $sms->setSuccessRate($percent);
            $this->smsRepository->add($sms);
            $persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
            $persistenceManager->persistAll();
            $this->getNameAndTel($receiverStr,$sms->getUid());
            $statu = $this->sendSMS($receiverArr, $sms->getModelNum(), $sms->getSender(), $customer, $sms->getUid());
            $errorTotal = 0;
            for ($i=0; $i < count($statu); $i++) { 
                if (array_key_exists('error',$statu[$i])&&$statu[$i]['error']!='OK') {
                    $errorTotal++;
                }
            }
            if ($errorTotal>0) {
                $newSms = $this->smsRepository->findByUid($sms->getUid());
                $successTotal = $countOn-$errorTotal;
                $newSms->setSuccessRate(sprintf('%.2f',$successTotal/$countUp)* 100);
                $this->smsRepository->update($newSms);
            }
            $this->addFlashMessage('短信已成功发送'.$successTotal.'条', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        }
        $this->redirect('list');
    }
    
    /**
     * action edit
     *
     * @param \Jykj\Mass\Domain\Model\Sms $sms
     * @ignorevalidation $sms
     * @return void
     */
    public function editAction(\Jykj\Mass\Domain\Model\Sms $sms)
    {
        //excel import
        if ($this->request->hasArgument('receiver')) {
            $file = $this->request->getArgument('receiver');
            $fI = GeneralUtility::split_fileref($file['name']);
            if (GeneralUtility::inList('xls,xlsx', $fI['fileext'])) {
                $objPHPReader = $this->objectManager->get($fI['fileext'] == 'xls' ? 'PHPExcel_Reader_Excel5' : 'PHPExcel_Reader_Excel2007');
                $objPHPExcel = $objPHPReader->load($file['tmp_name']);
                $currentSheet = $objPHPExcel->getSheet(0);
                $allRow = $currentSheet->getHighestRow();
                $i = 0;
                $telStr = '';
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    if ($currentSheet->getCell('B' . $currentRow)->getValue() != '') {
                        $name = $currentSheet->getCell('A' . $currentRow)->getValue();
                        $tel = $currentSheet->getCell('B' . $currentRow)->getValue();
                        $telStr .= $name . '<' . $tel . '>,';
                        $i++;
                    }
                }
                $telStr = rtrim($telStr, ',');
                $sms->setRecriver($telStr);
                $this->addFlashMessage('已成功上传“' . $i . '”条数据', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            } else {
                $this->addFlashMessage('文件格式不正确，请上传xls, xlsx格式文件。', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            }
        }
        $signatureArray = array();
        $tempArray = GeneralUtility::trimExplode('|', $this->settings['signature']);
        foreach ($tempArray as $signature) {
            $signatureArray[$signature] = $signature;
        }
        $this->view->assign('signatureArray', $signatureArray);
        $smsTemplateArray = array();
        $tempArray = GeneralUtility::trimExplode('|', $this->settings['templates']);
        foreach ($tempArray as $template) {
            $dataArray = GeneralUtility::trimExplode('^', $template);
            $smsTemplateArray[$dataArray[0]] = $dataArray[0] . ' - ' . $dataArray[1];
        }
        $this->view->assign('smsTemplateArray', $smsTemplateArray);
        $this->view->assign('sms', $sms);
    }
    
    /**
     * action update
     *
     * @param \Jykj\Mass\Domain\Model\Sms $sms
     * @return void
     */
    public function updateAction(\Jykj\Mass\Domain\Model\Sms $sms)
    {
        if ($sms->getSendStatus() == 0) {
            $this->addFlashMessage('短信已保存为草稿！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            $this->smsRepository->update($sms);
        } else {
            $receiverStr = $sms->getRecriver();
            $modelNum = $sms->getModelNum();
            $receiverArr = $this->getNameAndTel($receiverStr,$sms->getUid());
            $countUp = count(GeneralUtility::trimExplode(',', $receiverStr));
            $countOn = count($receiverArr);
            $percent = sprintf('%.2f', $countOn / $countUp) * 100;
            $sms->setTotal(count($receiverArr));
            $sms->setSendStatus(1);
            $sms->setSuccessRate($percent);
            $this->smsRepository->update($sms);
            $persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
            $persistenceManager->persistAll();
            $statu = $this->sendSMS($receiverArr, $sms->getModelNum(), $sms->getSender(), $customer, $sms->getUid());
            $errorTotal = 0;
            for ($i=0; $i < count($statu); $i++) { 
                if (array_key_exists('error', $statu[$i])) {
                    $errorTotal++;
                }
            }
            if ($errorTotal>0) {
                $newSms = $this->smsRepository->findByUid($sms->getUid());
                $successTotal = $countOn-$errorTotal;
                $newSms->setSuccessRate(sprintf('%.2f', $successTotal / $countUp) * 100);
                $this->smsRepository->update($newSms);
            }
            $this->addFlashMessage('短信已成功发送'.$successTotal.'条', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        }
        $this->redirect('list');
    }
    
    /**
     * action subInfo
     *
     * @param \Jykj\Mass\Domain\Model\Sms $sms
     * @return void
     */
    public function subInfoAction(\Jykj\Mass\Domain\Model\Sms $sms)
    {
        $receiverStr = $sms->getRecriver();
        $modelNum = $sms->getModelNum();
        $receiverArr = $this->getNameAndTel($receiverStr,$sms->getUid());
        $countUp = count(GeneralUtility::trimExplode(',', $receiverStr));
        $countOn = count($receiverArr);
        $percent = sprintf('%.2f', $countOn / $countUp) * 100;
        $sms->setTotal($countOn);
        $sms->setSendStatus(1);
        $sms->setSuccessRate($percent);
        $this->smsRepository->update($sms);
        $persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
        $persistenceManager->persistAll();
        // $customer = array('code' => $this->randCode(6));
        $customer = array();
        $statu = $this->sendSMS($receiverArr, $sms->getModelNum(), $sms->getSender(), $customer, $sms->getUid());
        $errorTotal = 0;
        for ($i=0; $i < count($statu); $i++) { 
            if (array_key_exists('error', $statu[$i])) {
                $errorTotal++;
            }
        }
        if ($errorTotal>0) {
            $newSms = $this->smsRepository->findByUid($sms->getUid());
            $successTotal = $countOn-$errorTotal;
            $newSms->setSuccessRate(sprintf('%.2f', $successTotal / $countUp) * 100);
            $this->smsRepository->update($newSms);
        }
        $this->addFlashMessage('短信已成功发送'.$successTotal.'条', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->redirect('list');
    }    

    /**
     * action tailLog
     *
     * @return void
     */
    public function tailLogAction()
    {
        $type = $this->request->hasArgument('type')?$this->request->getArgument('type'):'';
        if ($type=='1') {
            $massuid = $this->request->hasArgument('massuid')?$this->request->getArgument('massuid'):'';
            $keyword = $this->request->hasArgument('keyword')?$this->request->getArgument('keyword'):'';
            $form = $this->request->hasArgument('form')?$this->request->getArgument('form'):'';
            
            $logs = $this->logRepository->findTheTypeAndUid('sms',$massuid,$keyword);
            if ($_GET['tx_mass_sms']['@widget_0']['currentPage']) {
                $page = $_GET['tx_mass_sms']['@widget_0']['currentPage'];
            } else {
                $page = 1;
            }
            $this->view->assign('massuid', $massuid);
            $this->view->assign('logs', $logs);
            $this->view->assign('page', $page);
            $this->view->assign('type', $type);
            $this->view->assign('form', $form);
        }
    }

    /**
     * [deleteAction description]
     *
     * @param \Jykj\Mass\Domain\Model\Sms $sms [description]
     * @return [type]                           [description]
     */
    public function deleteAction(\Jykj\Mass\Domain\Model\Sms $sms)
    {
        $this->addFlashMessage('短信删除成功！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR);
        $this->smsRepository->remove($sms);
        $this->redirect('list');
    }
    
    /**
     * action multedelete
     *
     * @return void
     */
    public function multedeleteAction()
    {
        
    }
    
    /**
     * action success
     *
     * @return void
     */
    public function successAction()
    {
        
    }
    
    /**
     * 获取长字符串中的名字和电话
     *
     * @param [type] $longReceiverStr [description]
     * @param [type] $massuid         [description]
     * @return [type]                  [description]
     */
    public function getNameAndTel($longReceiverStr,$massuid)
    {
        $longreceiverArr = GeneralUtility::trimExplode(',', $longReceiverStr);
        $receiverArr = array();
        foreach ($longreceiverArr as $key => $value) {
            $name = strstr($value, '<', true);
            $tel = strstr($value, '<');
            $tel = rtrim($tel, '>');
            $tel = ltrim($tel, '<');
            if ($this->validTel($tel)) {
                $receiverArr[] = array(
                    'name' => $name,
                    'tel' => $tel
                );
            }else{
                if ($massuid!='') {
                    $sender = $GLOBALS['TSFE']->fe_user->user['name'] ? $GLOBALS['TSFE']->fe_user->user['name'] : $GLOBALS['TSFE']->fe_user->user['username'];
                    $message = $tel.'不是正确的手机号码！';
                    $this->addLogs('sms',$sender,$massuid,$value,0,$message);
                }
            }
        }
        return $receiverArr;
    }
    
    /**
     * 判断输入的字符串是否是手机号
     *
     * @param [type] $tel [description]
     * @return [bool] true || false
     */
    public function validTel($tel)
    {
        if (!preg_match('/^(1(([35][0-9])|(47)|[8][0126789]))\\d{8}$/', $tel)) {
            return false;
        }
        return true;
    }
    
    /**
     * 返回一个指定长度的随机数
     *
     * @param integer $length [description]
     * @return [type]          [description]
     */
    function randCode($length)
    {
        $min = pow(10, $length - 1);
        $max = pow(10, $length) - 1;
        return rand($min, $max);
    }
    
    /**
     * @param array  $receivers     [description]
     * @param [type] $smsModelNnm   [description]
     * @param [type] $signature     [description]
     * @param [type] $smsModelParam [description]
     * @param [type] $smsUid        [description]
     * @link https://api.alidayu.com/doc2/apiDetail.htm?spm=a3142.7395905.4.6.POO44h&apiId=25450
     * @return [type]              [description]
     */
    function sendSMS($receivers, $smsModelNnm, $signature, $smsModelParam=array(), $smsUid)
    {
        date_default_timezone_set('Asia/Shanghai');
        $sms = new \SmsDemo($this->settings['app_key'],$this->settings['app_secret']);
        $message = array();
        foreach ($receivers as $receiver) {
            $response = $sms->sendSms($signature, $smsModelNnm, $receiver['tel'], $smsModelParam, $smsUid);
            $queryres = $sms->queryDetails($receiver['tel'], date('Ymd'), 10, 1,$response->BizId);
            $sender = $GLOBALS['TSFE']->fe_user->user['name'] ? $GLOBALS['TSFE']->fe_user->user['name'] : $GLOBALS['TSFE']->fe_user->user['username'];
            $receive = $receiver['name'].'<'.$receiver['tel'].'>';
            if ($response->code!="OK") {
                $message[] = array('error' => $response->Message);
                $this->addLogs('sms',$sender,$smsUid,$receive,0,$response->Message);
                continue;
            }else{
                if (isset($queryres) && $queryres->code == 'OK') {
                    $message[] = array('error' => $queryres->Message);
                    $this->addLogs('sms',$sender,$smsUid,$receive,0,$queryres->Message);
                    continue;
                } else {
                    $this->addLogs('sms',$sender,$smsUid,$receive,1,$queryres->Message);
                    $message[] = array('success' => 'success');
                }
            }
        }
        return $message;
    }
    
    /**
     * 添加发送记录
     * @param [type] $type     [description]
     * @param [type] $sender   [description]
     * @param [type] $smsUid   [description]
     * @param [type] $receiver [description]
     * @param [type] $status   [description]
     * @param [type] $message  [description]
     */
    public function addLogs($type,$sender,$smsUid,$receiver,$status,$message)
    {
        $smsLog = new \Jykj\Mass\Domain\Model\Log();
        $smsLog->setType($type);
        $smsLog->setSender($sender);
        $smsLog->setSmsuid($smsUid);
        $smsLog->setReceiver($receiver);
        $smsLog->setSuatus($status);
        $smsLog->setMessage($message);
        $this->logRepository->add($smsLog);
    }
}